import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
  LoggerService,
} from '@nestjs/common';

@Catch()
export class HttpFilterFilter implements ExceptionFilter {
  constructor(private logger: LoggerService) {}
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    if (status.toString().startsWith('4')) {
      this.logger.error(exception.message || exception.name);
      let errorResponse = {};
      if (status === 401) {
        errorResponse = {
          data: exception.message || exception.name,
          message: '请求失败',
          success: false,
          code: 10000, // token过期
        };
      }
      if (status === 403) {
        errorResponse = {
          data: exception.message || exception.name,
          message: '请求失败',
          success: false,
          code: status, // 自定义code
        };
      }
      response.status(status);
      response.header('Content-Type', 'application/json; charset=utf-8');
      response.send(errorResponse);
    } else if (status.toString().startsWith('5')) {
      const errorResponse = {
        data: exception.message,
        message: '请求失败',
        success: false,
        code: status, // 自定义code
      };
      response.status(status);
      response.header('Content-Type', 'application/json; charset=utf-8');
      response.send(errorResponse);
    } else {
      response.status(status).json({
        code: status,
        timestamp: new Date().toISOString(),
        message: {},
      });
    }
  }
}
